﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using WebAPI;

WebApplicationOptions options = new WebApplicationOptions()
{
    Args = args,
    ContentRootPath = KernelCst.ContentRootPath,
    WebRootPath = KernelCst.WebRootPath
};
var builder = WebApplication.CreateBuilder(options);

var startup = new Startup(builder.Configuration);

//将默认ServiceProviderFactory指定为AutofacServiceProviderFactory
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(startup.ConfigureContainer);

builder.WebHost.UseKestrel().UseUrls("http://*:39274");

//加载配置文件
var folder = $"Settings.{Env.Current.KERNEL_ENVIRONMENT}";
string log = "";
log = $"Loading >>> {folder}";

AnsiConsole.Write(new Rule($"[green]{log}[/]")
    .RuleStyle(Style.Parse("gray"))
    .SquareBorder()
    .LeftJustified());

if (!Directory.Exists(folder))
{
    Directory.CreateDirectory(folder);
    File.Copy("Settings.Development/Log4net.config", $"{folder}/Log4net.config");
}

Log.Info(log);

if (string.IsNullOrWhiteSpace(Env.Current.KERNEL_CONFIG_CENTER))
{
    log = "从文件加载配置";
    Console.WriteLine(log);
    Log.Info(log);

    //注：在linux下，文件路径是区分大小写的
    builder.Configuration.SetBasePath(KernelCst.ContentRootPath)
    .AddJsonFile($"{folder}/appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"{folder}/Tenant.json", true, true)
    .AddJsonFile($"{folder}/IpRateLimiting.json", true, true)
    .AddJsonFile($"{folder}/skyapm.json", true, true);

    //优先加载加密后的配置文件
    if (File.Exists($"{KernelCst.ContentRootPath}{folder}/Builtin.bin"))
        builder.Configuration.AddEncryptedJsonFile($"{folder}/Builtin.bin", true, true);
    else
        builder.Configuration.AddJsonFile($"{folder}/Builtin.json", true, true);

}
else
{
    log = "从配置中心加载配置";
    Console.WriteLine(log);
    Log.Info(log);

    ConsulCfg cfg = new ConsulCfg()
    {
        Config = builder.Configuration,
        Folder = folder
    };
    cfg.AddConsul("appsettings.json");
    cfg.AddConsul("Tenant.json");
    cfg.AddConsul("IpRateLimiting.json");
    cfg.AddConsul("skyapm.json");
    cfg.AddConsul("Builtin.json");

}

//支持命令行参数或环境变量覆盖配置文件
builder.Configuration.AddEnvironmentVariables().AddCommandLine(args);

startup.ConfigureServices(builder.Services);

var app = builder.Build();

startup.Configure(app, app.Environment);

app.Run();
